package com.nguc.ngucpractice.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

/**
 * User:曹帅
 * Date:2020/8/7
 * Version:1.0
 */
public class OSSUtils {

    public static AssumeRoleResponse buildAliyunSTSCredentials(String key, String secret, String endpoint, String arn, String userId) throws ClientException {
        // STS
        DefaultProfile.addEndpoint(endpoint, "cn-beijing", "Sts", "sts.cn-hangzhou.aliyuncs.com");
        IClientProfile profile = DefaultProfile.getProfile("cn-beijing", key, secret);
        DefaultAcsClient client = new DefaultAcsClient(profile);

        final AssumeRoleRequest request = new AssumeRoleRequest();
        request.setMethod(MethodType.POST);
        request.setProtocol(ProtocolType.HTTPS);
        request.setDurationSeconds(60 * 60 * 1L);
        request.setRoleArn(arn);  // 要扮演的角色ID
        request.setRoleSessionName("user" + userId);
        // request.setPolicy(policy);

        // 生成临时授权凭证
        final AssumeRoleResponse response = client.getAcsResponse(request);
        /*
        String appKey = response.getCredentials().getAccessKeyId();  // 临时凭据AccessKeyId
        String appSecret = response.getCredentials().getAccessKeySecret();  // 临时凭据AccessKeySecret
        String securityToken = response.getCredentials().getSecurityToken();
        String expiration = response.getCredentials().getExpiration();
        System.out.println(appKey);
        System.out.println(appSecret);
        System.out.println(securityToken);
        System.out.println(expiration);*/
        return response;
    }

}
